package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.article.dto.ArticleDto;
import com.heima.article.dto.ArticleHomeDto;
import com.heima.article.dto.ArticleInfoDto;
import com.heima.article.entity.ApArticle;
import com.heima.article.entity.ApArticleContent;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.IApArticleContentService;
import com.heima.article.service.IApArticleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.task.ArticleHtmlTask;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import freemarker.template.TemplateException;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.SqlSessionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 文章信息表，存储已发布的文章 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-05-18
 */
@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements IApArticleService {

    @Autowired
    private IApArticleContentService articleContentService;

    @Autowired
    private ArticleHtmlTask articleHtmlTask;

    @Autowired
    private StringRedisTemplate redisTemplate;


    /**
     * 保存发布文章
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult<Long> saveArticle(ArticleDto dto) throws IOException, TemplateException {
        //1.将提交参数封装到PO对象中
        ApArticle article = new ApArticle();
        BeanUtils.copyProperties(dto, article);
        //2.判断用户操作类型（新增，更新）
        if (dto.getId() == null) {
            //2.1 处理文章新增
            //2.1.1 新增文章记录
            this.save(article);
            //2.1.2 新增文章内容记录
            ApArticleContent content = new ApArticleContent();
            content.setArticleId(article.getId());
            content.setContent(dto.getContent());
            articleContentService.save(content);
        } else {
            //2.2 处理文章更新
            //2.2.1 更新文章信息表
            this.updateById(article);
            //2.2.2 更新文章内容表
            LambdaUpdateWrapper<ApArticleContent> updateWrapper = new LambdaUpdateWrapper<>();
            //设置更新条件
            updateWrapper.eq(ApArticleContent::getArticleId, dto.getId());
            //设置更新字段
            updateWrapper.set(ApArticleContent::getContent, dto.getContent());
            articleContentService.update(updateWrapper);
        }
        //3.TODO 异步生成当前文章对
        // 应的静态html页面，将html文件上传到MinIO中
        articleHtmlTask.createAticleHtmlAndUpload(article.getId());
        //4.执行保存返回发布后文章ID
        return ResponseResult.okResult(article.getId());
    }


    /**
     * 首页加载文章列表
     *
     * @param dto  查询条件
     * @param type 0：加载最新  1：加载更多
     * @return
     */
    @Override
    public ResponseResult loadArticle(ArticleHomeDto dto, int type) {
        //TODO 判断是否为手机端  将来优化，将首页数据缓存到Redis中 抗并发
        if (dto.getLoaddir() == 1) {
            //从redis中加载文章类别
            String redisKeyPrefix = "leadnews:article:hot:page:";
            String key = redisKeyPrefix + dto.getChannelId();
            //从redis中获取zset中记录
            long start = 0;
            int end = dto.getSize() - 1;
            Set<String> strings = redisTemplate.opsForZSet().reverseRange(key, start, end);
            if (!CollectionUtils.isEmpty(strings)) {
                List<ApArticle> list = new ArrayList<>();
                for (String string : strings) {
                    ApArticle article = JSON.parseObject(string, ApArticle.class);
                    list.add(article);
                }
                return ResponseResult.okResult(list);
            }
        }

        //如果是后台管理-执行以下代码
        //1.封装查询条件
        LambdaQueryWrapper<ApArticle> queryWrapper = new LambdaQueryWrapper<>();
        //1.1 设置文章未删除 未下架
        queryWrapper.eq(ApArticle::getIsDelete, false);
        queryWrapper.eq(ApArticle::getIsDown, false);
        //1.2 设置频道ID条件
        if (dto.getChannelId() != null) {
            queryWrapper.eq(ApArticle::getChannelId, dto.getChannelId());
        }
        //1.3 设置时间条件
        if (type == 1) {
            //上拉加载更多，判断数据库中文章发布时间小于传入minTime(本页最后一条记录发布时间)
            queryWrapper.le(ApArticle::getPublishTime, dto.getMinTime());
        } else {
            //下拉获取最新，判断数据库中文章发布时间大于传入maxTime(本页第一条记录发布时间)
            queryWrapper.ge(ApArticle::getPublishTime, dto.getMaxTime());
        }

        //1.4 设置排序：根据发布时间排序
        queryWrapper.orderByDesc(ApArticle::getPublishTime);

        //2.封装分页对象
        IPage<ApArticle> page = new Page<>(1, dto.getSize());

        ///3.执行分页查询
        page = this.page(page, queryWrapper);

        //4.封装响应结果
        return new PageResponseResult(1L, dto.getSize(), page.getTotal(), page.getRecords());
    }


    /**
     * 根据文章ID 查询文章详情信息
     *
     * @param dto 文章ID
     * @return
     */
    @Override
    public ResponseResult loadArticleInfo(ArticleInfoDto dto) {
        //1.根据传入文章ID查询文章对象,判断文章状态
        ApArticle article = this.getById(dto.getArticleId());
        if (article == null || article.getIsDelete() || article.getIsDown()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //2.根据文章ID查询文章内容
        LambdaQueryWrapper<ApArticleContent> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ApArticleContent::getArticleId, dto.getArticleId());
        ApArticleContent content = articleContentService.getOne(queryWrapper);

        //3.按照接口文档封装业务结果数据
        HashMap<String, Object> mapResult = new HashMap<>();
        mapResult.put("config", article);
        mapResult.put("content", content);
        return ResponseResult.okResult(mapResult);
    }
}
